package com.jn.okhttp.views;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.jn.okhttp.R;


import com.jn.okhttp.contract.TranslateApi;
import com.jn.okhttp.entity.TranslateResponse;
import com.jn.okhttp.utils.RetrofitClient;

import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback; // 确保导入 Retrofit 的 Callback
import retrofit2.Response;

public class TranslateActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, TextToSpeech.OnInitListener {

    private EditText etSourceText, etTranslatedText;
    private Spinner spSourceLanguage, spTargetLanguage;
    private Button btnTranslate, clearBtn;
    private ImageView ivSwap;
    private String sourceLanguage, targetLanguage;
    private TextToSpeech tts;
    private TranslateApi translateApi;

    public TranslateActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_translate);

        // 初始化控件
        etSourceText = findViewById(R.id.etSourceText);
        etTranslatedText = findViewById(R.id.etTranslatedText);
        spSourceLanguage = findViewById(R.id.spSourceLanguage);
        spTargetLanguage = findViewById(R.id.spTargetLanguage);
        btnTranslate = findViewById(R.id.btnTranslate);
        ivSwap = findViewById(R.id.ivSwap);
        clearBtn = findViewById(R.id.btnClear);
        // 初始化Retrofit
        translateApi = RetrofitClient.getClient().create(TranslateApi.class);

        // 初始化Spinner
        String[] languages = {"Auto", "English", "Chinese"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, languages);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spSourceLanguage.setAdapter(adapter);
        spTargetLanguage.setAdapter(adapter);

        spSourceLanguage.setOnItemSelectedListener(this);
        spTargetLanguage.setOnItemSelectedListener(this);

        // 默认选择
        spSourceLanguage.setSelection(0);
        spTargetLanguage.setSelection(2);

        // 设置翻译按钮点击事件
        btnTranslate.setOnClickListener(v -> translateText());

        // 设置互换按钮点击事件
        ivSwap.setOnClickListener(v -> swapLanguages());

        // 初始化TTS
        tts = new TextToSpeech(this, this);
        // 设置清空按钮点击事件
        clearBtn.setOnClickListener(v -> clearText());
        // 设置按钮点击事件
        Button btnInstallTTSData = findViewById(R.id.btn_install_tts_data);
        btnInstallTTSData.setOnClickListener(v -> installMissingData());
    }

    private void clearText() {
        etSourceText.setText("");
        etTranslatedText.setText("");
    }

    private void translateText() {
        String sourceText = etSourceText.getText().toString();
        if (sourceText.isEmpty()) {
            Toast.makeText(this, "请输入要翻译的内容", Toast.LENGTH_SHORT).show();
            return;
        }

        // 调用API进行翻译
        translateApi.translate(sourceText).enqueue(new Callback<TranslateResponse>() {
            @Override
            public void onResponse(Call<TranslateResponse> call, Response<TranslateResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    TranslateResponse translateResponse = response.body();
                    if (translateResponse.getCode() == 200) {
                        String translatedText = translateResponse.getResult().getTargetText();
                        etTranslatedText.setText(translatedText);
                        speakOut(translatedText);
                    } else {
                        Toast.makeText(TranslateActivity.this, "翻译失败: " + translateResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TranslateActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<TranslateResponse> call, Throwable t) {
                Toast.makeText(TranslateActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void swapLanguages() {
//        String temp = sourceLanguage;
//        sourceLanguage = targetLanguage;
//        targetLanguage = temp;
//
//        int sourceIndex = getSourceIndex(sourceLanguage);
//        int targetIndex = getTargetIndex(targetLanguage);
//
//        spSourceLanguage.setSelection(sourceIndex);
//        spTargetLanguage.setSelection(targetIndex);
        // 获取当前选中的语言索引
        int sourceIndex = spSourceLanguage.getSelectedItemPosition();
        int targetIndex = spTargetLanguage.getSelectedItemPosition();

        // 交换索引
        spSourceLanguage.setSelection(targetIndex);
        spTargetLanguage.setSelection(sourceIndex);
    }

    private int getSourceIndex(String language) {
        switch (language) {
            case "Auto":
                return 0;
            case "English":
                return 1;
            case "Chinese":
                return 2;
            default:
                return 0;
        }
    }

    private int getTargetIndex(String language) {
        switch (language) {
            case "Auto":
                return 0;
            case "English":
                return 1;
            case "Chinese":
                return 2;
            default:
                return 0;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if (parent.getId() == R.id.spSourceLanguage) {
            if (pos == 0) {
                sourceLanguage = "Auto";
            } else if (pos == 1) {
                sourceLanguage = "en";
            } else {
                sourceLanguage = "zh";
            }
        } else if (parent.getId() == R.id.spTargetLanguage) {
            if (pos == 0) {
                targetLanguage = "Auto";
            } else if (pos == 1) {
                targetLanguage = "en";
            } else {
                targetLanguage = "zh";
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Do nothing
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            // 检查 TTS 引擎是否存在
            if (!isTTSEngineAvailable()) {
                Toast.makeText(this, "TTS 引擎不可用", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查特定语言的数据包是否已安装
            Locale locale = Locale.CHINA;
            int result = tts.isLanguageAvailable(locale);
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Toast.makeText(this, "语言数据缺失或不受支持", Toast.LENGTH_SHORT).show();
                installMissingData();
            } else {
                tts.setLanguage(locale);
                // 其他初始化代码
                speakOut("哈喽，这是一个测试。");
            }
        } else {
            Toast.makeText(this, "初始化失败", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isTTSEngineAvailable() {
        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentServices(new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA), 0);
        return !list.isEmpty();
    }

    private void installMissingData() {
        Intent installIntent = new Intent();
        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        startActivity(installIntent);
    }

    private void speakOut(String text) {
        if (tts != null) {
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }

    @Override
    protected void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }


}